package com.t235.gc.auth.service;


import com.t235.gc.entity.SysManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set;

@Service("rbacService")
@Slf4j
public class RbacServiceImpl implements RbacService {
    private AntPathMatcher antPathMatcher=new AntPathMatcher();
    @Autowired
    UserService userService;
    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication auto) {
        //访问路径时进入该方法
        Object principal = auto.getPrincipal();
        boolean hasPermisson=false;
        if(principal!=null && principal instanceof UserDetails){
            //获得登入用户名
            String username = ((UserDetails) principal).getUsername();
        /*if(principal!=null){
            String username=(String) principal;*/
            System.out.println(username);
            //获取请求登入资源
            SysManager sysManager= (SysManager) userService.loadUserByUsername(username);
            //保存可以访问的路径
            Set<String> urls=new HashSet<>();
            //获得当前访问路径
            String requestURI = request.getRequestURI();
            //循环user表中的role集合
            sysManager.getRoles().forEach(role -> {
                //循环role表中的menu集合 表数据在loadUserByUsername方法已经添加了
                role.getMenus().forEach(menu -> {
                    if(StringUtils.hasText(menu.getInterfaceurl())){
                        urls.add(menu.getInterfaceurl());//添加该角色可以访问的路径
                    }
                });
            });
            for (String url:urls) {
                if(antPathMatcher.match(url,requestURI)){
                    hasPermisson=true;
                }
            }
            log.debug("{},访问路径:{},可以访问路径{}",hasPermisson,requestURI,urls);
        }
        return hasPermisson;
    }
}
